package com.qingcloud.adminbackend.controller;


import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qingcloud.adminbackend.base.AjaxResult;
import com.qingcloud.adminbackend.constant.WamingConstant;
import com.qingcloud.adminbackend.entity.equipment.ModelDTO;
import com.qingcloud.adminbackend.entity.sysstation.*;
import com.qingcloud.adminbackend.service.ISysStationService;
import com.qingcloud.adminbackend.service.ISysUserService;
import com.qingcloud.adminbackend.service.impl.BaseServiceImpl;
import com.qingcloud.adminbackend.utils.CookieUtil;
import com.qingcloud.adminbackend.utils.PoiExcelExport;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 监测点信息表 前端控制器
 * </p>
 *
 * @author luozehua
 * @since 2019-04-10
 */
@Api(value = "监测点管理", description = "监测点管理")
@RestController
@RequestMapping("/sys_station")
public class SysStationController {

    @Resource
    private ISysStationService sysStationService;
    @Resource
    private BaseServiceImpl baseService;
    @Resource
    private ISysUserService sysUserService;

    @Value("${file.rootpath}")
    private String ROOTPATH;

    /**
     * 获取监测点详情
     *
     * @return
     */
    @ApiOperation(value = "获取监测点详情", notes = "获取监测点详情", response = StationDetailsDTO.class)
    @ApiImplicitParam(name = "stationId", value = "站点编号", dataType = "string", paramType = "query", defaultValue = "17001")
    @GetMapping(value = "/details")
    public AjaxResult details(@RequestParam("stationId") String stationId, HttpServletRequest request) {
        String userId = CookieUtil.getUserId(request);
        boolean admin = CookieUtil.isAdmin(request);
        StationDetailsDTO details = sysStationService.details(stationId, userId, admin);
        return new AjaxResult(WamingConstant.SUCCESS, "", details);
    }

    @ApiOperation(value = "批量删除监测点", notes = "批量删除监测点")
    @ApiImplicitParam(name = "stationIds", value = "站点编号列表", dataType = "list", paramType = "body", defaultValue = "")
    @PostMapping(value = "/delete")
    public AjaxResult delete(@RequestBody List<String> stationIds, HttpServletRequest request) {
        String userId = CookieUtil.getUserId(request);
        int flag = sysStationService.delete(stationIds, userId);
        if (flag == 0) {
            return new AjaxResult(WamingConstant.PART_SUCCESS, "请选择监测点", "!");
        } else if (flag == -1) {
            return new AjaxResult(WamingConstant.PART_SUCCESS, "监测点有绑定设备", "");
        } else {
            return new AjaxResult(WamingConstant.SUCCESS, "", "删除成功");
        }
    }

    @ApiOperation(value = "监测点上线", notes = "监测点上线")
    @ApiImplicitParam(name = "stationIds", value = "站点编号列表", dataType = "list", paramType = "body", defaultValue = "")
    @PostMapping(value = "/online")
    public AjaxResult online(@RequestBody List<String> stationIds) {
        sysStationService.online(stationIds);
        return new AjaxResult(WamingConstant.SUCCESS, "", "上线成功");
    }

    @ApiOperation(value = "监测点下线", notes = "监测点下线")
    @ApiImplicitParam(name = "stationIds", value = "站点编号列表", dataType = "list", paramType = "body", defaultValue = "")
    @PostMapping(value = "/offline")
    public AjaxResult offline(@RequestBody List<String> stationIds) {
        sysStationService.offline(stationIds);
        return new AjaxResult(WamingConstant.SUCCESS, "", "下线成功");
    }

    @ApiOperation(value = "监测点批量设置共享", notes = "监测点批量设置共享")
    @ApiImplicitParam(name = "stationShareTimeDTO", value = "设置共享信息", required = true, dataType = "StationShareTimeDTO")
    @PostMapping(value = "/share")
    public AjaxResult share(@RequestBody StationShareTimeDTO stationShareTimeDTO, HttpServletRequest request) {
        String userId = CookieUtil.getUserId(request);
        Integer flag = sysStationService.share(stationShareTimeDTO, userId);
        if (flag == 0) {
            return new AjaxResult(WamingConstant.PART_SUCCESS, "请选择监测点", "");
        }
        return new AjaxResult(WamingConstant.SUCCESS, "", "设置成功");
    }

    @ApiOperation(value = "监测点批量绑定", notes = "监测点批量绑定")
    @PostMapping(value = "/batchMount")
    @ApiImplicitParams({@ApiImplicitParam(name = "businessType", value = "业务类型（1：网格化，2:健康云）", defaultValue = "2", required = true, dataType =
            "String", paramType = "query")})
    public AjaxResult batchMount(@RequestParam("excelFile") MultipartFile excelFile, Integer businessType, HttpServletRequest request) {
        String userId = CookieUtil.getUserId(request);
        boolean admin = CookieUtil.isAdmin(request);
        return sysStationService.batchMount(excelFile, businessType, userId, admin);
    }

    @ApiOperation(value = "监测点绑定", notes = "监测点绑定", response = MountStationInfo.class)
    @ApiImplicitParam(name = "stationId", value = "站点编号", dataType = "string", paramType = "path", defaultValue = "")
    @GetMapping(value = "/mount/{stationId}")
    public AjaxResult mount(@PathVariable("stationId") String stationId) throws UnsupportedEncodingException {
        stationId = java.net.URLDecoder.decode(stationId, "UTF-8");
        return new AjaxResult(WamingConstant.SUCCESS, "", sysStationService.mount(stationId));
    }


    @ApiOperation(value = "设置监测点共享时查询监测点", notes = "设置监测点共享时查询监测点", response = StationShare.class)
    @PostMapping(value = "/selectShare")
    public AjaxResult selectShare(@RequestBody List<String> stationIds) {
        // IPage<StationShareDTO> stationShareDTO = sysStationService.selectShareByPage(shareStationPageDTO);
        List<StationShare> stationShareDTO = sysStationService.selectShare(stationIds);
        return new AjaxResult(WamingConstant.SUCCESS, "", stationShareDTO);
    }

    @ApiOperation(value = "添加检测点", notes = "添加检测点")
    @PostMapping(value = "/opt")
    public AjaxResult addStation(@RequestBody AddStationDTO addStationDTO, HttpServletRequest request) {
        String userId = CookieUtil.getUserId(request);
        Integer flag = sysStationService.addStation(addStationDTO, userId);
        if (flag == -1) {
            return new AjaxResult(WamingConstant.FAILURE, "位置信息错误", "");
        } else if (flag == 2) {
            return new AjaxResult(WamingConstant.SUCCESS, "", "添加成功");
        } else if (flag == -2) {
            return new AjaxResult(WamingConstant.FAILURE, "添加失败", "");
        } else if (flag == 3) {
            return new AjaxResult(WamingConstant.SUCCESS, "", "修改成功");
        } else if (flag == -3) {
            return new AjaxResult(WamingConstant.FAILURE, "修改失败", "");
        } else if (flag == -4) {
            return new AjaxResult(WamingConstant.FAILURE, "监测点编号已存在", "");
        } else if (flag == -5) {
            return new AjaxResult(WamingConstant.FAILURE, "订单已不存在", "");
        } else {
            return new AjaxResult(WamingConstant.FAILURE, "操作失败", "");
        }
    }

    @ApiOperation(value = "分页查询监测点管理列表", notes = "分页查询监测点管理列表", response = StationListDTO.class)
    @PostMapping(value = "/findStationList")
    public AjaxResult findPageStationList(@RequestBody StationListPara stationListPara, HttpServletRequest request) {
        String userId = CookieUtil.getUserId(request);
        List<ModelDTO> stationIds = null;
        if (stationListPara != null) {
            stationIds = baseService.getStationIds(userId, stationListPara.getOrderIds(), stationListPara.getOrgIds(), null, null, true);
        }
        IPage<StationListDTO> listStation = null;
        if (stationIds != null && stationIds.size() > 0) {
            listStation = sysStationService.listStation(stationListPara, stationIds, userId);
        }
        if (listStation == null) listStation = new Page<>();
        return new AjaxResult(WamingConstant.SUCCESS, "", listStation);
    }

    @ApiOperation(value = "监测点管理列表", notes = "监测点管理列表", response = StationListDTO.class)
    @PostMapping(value = "/export")
    public AjaxResult exportData(@RequestBody StationListPara stationListPara, HttpServletRequest request, HttpServletResponse response) throws IOException {
        String userId = CookieUtil.getUserId(request);
        List<ModelDTO> stationIds = null;
        if (stationListPara != null) {
            stationIds = baseService.getStationIds(userId, stationListPara.getOrderIds(), stationListPara.getOrgIds(), null, null, true);
        }
        List<StationExportDTO> listStation = new ArrayList<>();
        if (stationIds != null && stationIds.size() > 0) {
            listStation = sysStationService.exportData(stationListPara, stationIds, userId);
            sysStationService.hanldShareInfo(listStation);
        }
        String fileName = "监测点" + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy年MM月dd日HH时mm分ss秒")) + ".xlsx";
        String sheetName = "监测点列表";

        String[] titleName = {"监测点名称", "设备编号", "监测点状态", "监测点种类", "空间", "省市区县", "街道", "地址", "楼宇", "楼层", "房间/区域", "共享状态", "共享时段", "所属订单"};// 列名
        String[] titleColumn = {"stationId", "equipmentId", "stationStatusDesc", "stationCatagoryDesc", "moCapation", "proCityDis", "road", "address",
                "build", "floor", "room", "sharedDesc", "shareInfo", "orderName"};
        int[] titleSize = {10, 10, 20, 20, 20, 20, 20, 10, 30, 30, 30, 10, 20, 30};

        String fileDir = ROOTPATH + "/temp";
        File dir = new File(fileDir);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        String file = fileDir + "/" + fileName;
        PoiExcelExport poiExcelExport = new PoiExcelExport(file, sheetName);
        poiExcelExport.wirteExcel(titleColumn, titleName, titleSize, listStation);
        AjaxResult result = new AjaxResult();
        String url = request.getContextPath() + "/file/view/temp/" + fileName;
        Map<String, String> resultMap = new HashMap<>(1);
        resultMap.put("url", url);
        result.setResult(resultMap);
        result.setErroCode(2000);
        return result;
    }

    @ApiOperation(value = "健康空气设备监测点批量导入Api", notes = "健康空气设备监测点批量导入Api")
    @ApiImplicitParams({@ApiImplicitParam(name = "businessType", value = "业务类型（1：网格化，2:健康云）", defaultValue = "1", required = false, dataType =
            "String", paramType = "query"), @ApiImplicitParam(name = "orderId", value = "订单id", defaultValue = "1", required = false, dataType =
            "String", paramType = "query"),})
    @PostMapping("/equipmentStationExcel")
    public AjaxResult equipmentStationExcel(@ApiParam("上传的文件") MultipartFile file, String businessType, String orderId, HttpServletRequest request) throws IOException {
        if (file == null) return new AjaxResult(WamingConstant.FAILURE, "解析失败", null);
        String name = file.getOriginalFilename();// 获取上传文件名,包括路径
        long size = file.getSize();
        if ((name == null || name.equals("")) && size == 0) {
            return new AjaxResult(WamingConstant.FAILURE, "解析失败", null);
        }
        String userId = CookieUtil.getUserId(request);
        //网格化
        if ("1".equals(businessType)) {
            //网格化监测点导入
            return sysStationService.stationExcel(file, userId, orderId);
        }
        //健康空气
        if ("2".equals(businessType)) {
            //健康空气监测点导入
            return sysStationService.stationExcelJKKQ(file, userId, orderId);
        }
        return new AjaxResult(WamingConstant.FAILURE, "请传入业务种类");
    }

    @ApiOperation(value = "登录用户获取监测数据权限", notes = "登录用户获取监测数据权限")
    @PostMapping(value = "/getStationDataPermissions")
    public AjaxResult getStationDataPermissions(String userId, String workType) {

        //原蛙鸣用户的监测点权限
        List<ModelDTO> wamingStationList = baseService.getStationIds(userId, null,null, workType, 1, false).stream()
                .filter(it -> StrUtil.isNotBlank(it.getMoId())).collect(Collectors.toList());

        //原普通用户的监测点权限
        List<ModelDTO> stationList = baseService.getUserStationIds(userId, workType).stream()
                .filter(it -> StrUtil.isNotBlank(it.getMoId())).collect(Collectors.toList());

        //合并起来返回
        stationList.addAll(wamingStationList);
        return new AjaxResult(WamingConstant.SUCCESS, "", new HashSet<>(stationList));
    }
}

